const express = require('express')
const router = express.Router()
const fs = require('fs')
const path = require('path')
const { mySend, Vtoken, checkParams } = require('../utils/index')
const { to } = require('await-to-js')
const public = path.join(__dirname, '../public/user')
const temp = path.join(__dirname, '../public/temp')
const normalUpload = path.join(__dirname, '../public/normalUpload')
// const multiparty = require('multiparty');

const multipart = require('connect-multiparty');
const multipartMiddleware = multipart();
//upload delete update list adminList

router.post('/upload',multipartMiddleware, async (req, res) => {
    const { token } = req.body
    const user = await Vtoken(token)
    if (!user) {
      return mySend(res, 314, 'token不存在或已过期')
    }
    let files = req.files.files
    if(!files){
        return mySend(res, 1, '请选择文件')
    } 
    if(!files.length) files = [files]
    let myPath = temp + '/' + user.username;
    let isExists = fs.existsSync(myPath)
    if (!isExists) {
        fs.mkdirSync(myPath)
    }
    let fileList = []
    files.forEach((file) => {
        let readStream=fs.createReadStream(file.path);
        let writeStream=fs.createWriteStream(myPath + '/' + file.originalFilename);
        readStream.pipe(writeStream);
        readStream.on('end',() => {
         fs.unlinkSync(file.path);
        });
        fileList.push('/temp/' + user.username + '/' + file.originalFilename)
    })
    mySend(res, 0, '成功', fileList)
})

router.post('/normalUpload',multipartMiddleware, async (req, res) => {
    const { token } = req.body
    const user = await Vtoken(token)
    if (!user) {
      return mySend(res, 314, 'token不存在或已过期')
    }
    let files = req.files.files
    if(!files){
        return mySend(res, 1, '请选择文件')
    } 
    if(!files.length) files = [files]
    let myPath = normalUpload;
    let isExists = fs.existsSync(myPath)
    if (!isExists) {
        fs.mkdirSync(myPath)
    }
    let fileList = []
    files.forEach((file) => {
        let readStream=fs.createReadStream(file.path);
        let arr = file.path.split('\\')
        let newfileName = arr[arr.length - 1]
        let writeStream=fs.createWriteStream(newfileName);
        readStream.pipe(writeStream);
        readStream.on('end',() => {
         fs.unlinkSync(file.path);
        });
        let str = newfileName.substring(5)
        fileList.push('/public/normalUpload/' + str)
    })
    mySend(res, 0, '成功', fileList)
})

router.post('/add', async (req, res) => {
    const { fileList, token } = req.body
    const checked = checkParams({ fileList, token })
    if (checked) return mySend(res, 1, checked)
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    fileList.forEach(file => {
        let filePath = path.join(__dirname, '../public/' + file)
        let readStream=fs.createReadStream(filePath);
        let writeStream=fs.createWriteStream(public + '/' + user.username + '/' + file.substring(5 + user.username.length + 1));
        readStream.pipe(writeStream);
        readStream.on('end',() => {
         fs.unlinkSync(filePath);
        });

    })
    return mySend(res, 0, '成功')
})

router.post('/delete', async (req, res) => {
    const { filename, token } = req.body
    const checked = checkParams({ filename, token })
    if (checked) return mySend(res, 1, checked)
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    let myPath = public + '/' + user.username;
    
    const exists = fs.existsSync(myPath + '/' + filename)
    if (!exists) return mySend(res, 1, '文件不存在')

    fs.unlinkSync(myPath + '/' + filename)
    return mySend(res, 0, '删除成功')

})

router.post('/update', async (req, res) => {
    const { filename, newFilename, token } = req.body
    const checked = checkParams({ filename, newFilename, token })
    if (checked) return mySend(res, 1, checked)
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')

    let myPath = public + '/' + user.username;
    fs.renameSync(myPath + '/' + filename, myPath + '/' + newFilename)
    return mySend(res, 0, 'ok')

})

router.post('/list', async (req, res) => {
    const { token, size = 10, current = 1 } = req.body
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    let myPath = public + '/' + user.username;
    let isExists = fs.existsSync(myPath)
    if (!isExists) {
        fs.mkdirSync(myPath)
    }
    let fsArray = fs.readdirSync(myPath)
    let data = {
        total: fsArray.length,
        size,
        current,
        fileList: []
    }

    for(let i = (current - 1) * size; i < current * size; i ++){
        if(!fsArray[i]) break
        let item = Object.assign({fileName: fsArray[i]}, fs.statSync(myPath + '/' + fsArray[i]))
        data.fileList.push(item)
    }
    return mySend(res, 0, 'success', data)
})

router.post('/adminList', async (req, res) => {
    const { token, current = 1, size = 10, username } = req.body
    const user = await Vtoken(token)
    if (!user) {
      return mySend(res, 314, 'token不存在或已过期')
    }
    if(user.role !== 1) return mySend(res, 1, '你的权限不能查看其他用户文件')

    let fileList = []

    let files = username ? [username] : fs.readdirSync(public)
    let total = 0
    files.forEach(item => {
        let fsArray = fs.readdirSync(public + '/' +item)
        for(let i = 0; i < fsArray.length; i ++){
            if(total >= (current - 1) * size && total < current * size){
                fileList.push(Object.assign({username: item, fileName: fsArray[i], key: total}, fs.statSync(public + '/' + item  + '/' + fsArray[i])))
            }
            total ++
        }
    })
    let body = {
        total,
        size,
        current,
        fileList
    }
    return mySend(res, 0, 'success', body)
})

router.post('/adminDelete', async (req, res) => {
    const { filename, username, token } = req.body
    const checked = checkParams({ filename, username, token })
    if (checked) return mySend(res, 1, checked)
    const user = await Vtoken(token)
    if (!user) return mySend(res, 314, 'token不存在或已过期')
    if(user.role !== 1) return mySend(res, 1, '你的权限不能删除其他用户文件')
    let myPath = public + '/' + username;
    
    const exists = fs.existsSync(myPath + '/' + filename)
    if (!exists) return mySend(res, 1, '文件不存在')

    fs.unlinkSync(myPath + '/' + filename)
    return mySend(res, 0, '删除成功')

})

module.exports = router